import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login'
import Admin from '../views/Admin'
import Dormitorymannager from '../views/Dormitorymannager'
import Homemastermannager from '../views/Homemastermannager'
import Addstudent from '../views/Addstudent'
import Studentmannager from '../views/Studentmannager'
import Editdormitory from '../views/Editdormitory'
import Edithomemaster from '../views/Edithomemaster'
import Editstudent from '../views/Editstudent'
import Homemaster from '../views/Homemaster'
import HomeHM from '../views/HomeHM'
import Student from '../views/Student'
import HomeS from '../views/HomeS'
import SendApply from '../views/SendApply'
import EditApply from '../views/EditApply'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '登录',
    component: Login
  },
  {
    path: '/admin',
    name: '管理员',
    component: Admin,
    redirect:'/dormitorymannager',
    children:[
      {
        path: '/dormitorymannager',
        name: '查询并管理宿舍',
        component: Dormitorymannager,
      },
      {
        path: '/homemastermannager',
        name: '查询并管理宿管',
        component: Homemastermannager
      },
      {
        path:'/editdormitory',
        name:'编辑宿舍信息',
        component: Editdormitory
      },
      {
        path:'/edithomemaster',
        name:'编辑宿管信息',
        component: Edithomemaster
      },
      {
        path: '/addstudent',
        name: '增加学生',
        component: Addstudent
      },
    ]
  },
  {
    path:'/homemaster',
    name:'宿管',
    component:Homemaster,
    redirect:'/homeHM',
    children:[
      {
        path: '/studentmannager',
        name: '查询并管理学生',
        component: Studentmannager
      },
      {
        path:'/editstudent',
        name:'编辑学生信息',
        component: Editstudent
      },
      {
        path:'/homeHM',
        name:'宿管主页',
        component: HomeHM
      }
    ]
  },
  {
    path:'/student',
    name:'学生',
    component:Student,
    redirect:'/homes',
    children:[
      {
        path:'/homes',
        name:'学生信息主页',
        component:HomeS
      },
      {
        path:'/sendapply',
        name:'学生信息主页',
        component:SendApply
      },
      {
        path:'/editapply',
        name:'修改申请',
        component:EditApply
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  let token = JSON.parse(localStorage.getItem('token'))
  if(to.path == '/'){
    next();
  }else{
    axios.get(`http://localhost:8081/JWT/check/${token}`).then(function(resp){
      if(!resp.data){
        alert('登录失效，请重新登录')
        next({path:'/'})
      }else 
      next()
    })
  }
})

export default router
